//
//  LoopHomeTableViewCell.swift
//  LoopWeibo
//
//  Created by loop安 on 2016/12/11.
//  Copyright © 2016年 loop. All rights reserved.
//

import UIKit
import SDWebImage

private let margin:CGFloat = 8
private let imageMargin:CGFloat = 4
private let maxWidth = screenWidth - 2 * margin
private let itemWidth = (maxWidth - 2 * imageMargin) / 3
class LoopHomeTableViewCell: UITableViewCell {

    //头像
    @IBOutlet weak var imgIcon: UIImageView!
    //用户名
    @IBOutlet weak var lblName: UILabel!
    //时间
    @IBOutlet weak var lblTime: UILabel!
    //来源
    @IBOutlet weak var lblSource: UILabel!
    //内容
    @IBOutlet weak var lblText: YYLabel!
    //认证
    @IBOutlet weak var imgVerified: UIImageView!
    //会员等级
    @IBOutlet weak var imgVip: UIImageView!
    //头像遮挡视图
    @IBOutlet weak var coverView: UIView!
    //图片显示视图
    @IBOutlet weak var colPicture: LoopPictureCollectionView!
    //图片显示视图高度约束
    @IBOutlet weak var colHeightLayout: NSLayoutConstraint!
    //图片显示视图宽度约束
    @IBOutlet weak var colWidthLayout: NSLayoutConstraint!
    //图片显示视图顶部约束
    @IBOutlet weak var colTopLayout: NSLayoutConstraint!
    //图片显示视图布局约束
    @IBOutlet weak var colFlowLayout: UICollectionViewFlowLayout!
    
    //转发微博的内容
    @IBOutlet weak var lblRepostTitle: YYLabel!
    //工具栏转发按钮
    @IBOutlet weak var btnRepost: UIButton!
    //工具栏评论按钮
    @IBOutlet weak var btnComment: UIButton!
    //工具栏点赞按钮
    @IBOutlet weak var btnLike: UIButton!
    //cell中的最后一个控件
    @IBOutlet weak var showdView: UIView!
    
    
    var viewModel:LoopStatusCellViewModel?{
        didSet{
            //绑定数据
            imgIcon.sd_setImage(with: viewModel?.iconUrl)
            lblName.text = viewModel?.statusModel?.user?.name
            lblTime.text = viewModel?.timeText
            lblSource.text = viewModel?.sourceText
//            lblText.text = viewModel?.statusModel?.text
            lblText.attributedText = viewModel?.finallyContent
            imgVerified.image = viewModel?.verifitedImage
            imgVip.image = viewModel?.mbrankImage
            btnRepost.setTitle(viewModel?.reposts_count, for: .normal)
            btnComment.setTitle(viewModel?.comments_count, for: .normal)
            btnLike.setTitle(viewModel?.attitudes_count, for: .normal)
            
            //头像认证标识设置
            if viewModel?.statusModel?.user?.mbrank != 0 {
                lblName.textColor = #colorLiteral(red: 0.9529411793, green: 0.6862745285, blue: 0.1333333403, alpha: 1)
            }
            if viewModel?.statusModel?.user?.verified_type == -1 {
                coverView.isHidden = true
            }
            //由于有两个不同的配图视图数据
            //所以需要修改count的获取
            let count = viewModel?.imageArray?.count ?? 0
            //根据是否有图片,修改collectionView的顶部约束
            colTopLayout.constant = (count == 0 ? 0 : margin)
            
            let result = calculateCollectionSize(count: count)
            colWidthLayout.constant = result.picSize.width
            colHeightLayout.constant = result.picSize.height
            
            colFlowLayout.itemSize = calculateCollectionSize(count: count).cellSize
            
            colPicture.pictureInfo = viewModel?.imageArray
            
            lblRepostTitle?.attributedText = viewModel?.retweetFinallyContent
            
            //void(^YYTextAction)(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect)
            lblText.highlightTapAction = {(containerView,text,range,rect)->() in
                
                let str = (text.string as NSString).substring(with: range)
                
                if str.hasPrefix("http") {
                    
                    let vc = LoopWebViewController()
                    vc.urlString = str
                    
                    self.findNavigationController()?.pushViewController(vc, animated: true)
                }
            }
            
            if viewModel?.statusModel?.retweeted_status != nil {
            
                lblRepostTitle.highlightTapAction = {(containerView,text,range,rect)->() in
                    let str = (text.string as NSString).substring(with: range)
                    
                    if str.hasPrefix("http") {
                        
                        let vc = LoopWebViewController()
                        vc.urlString = str
                        
                        self.findNavigationController()?.pushViewController(vc, animated: true)
                    }
                }
            
            }
        }
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
//        self.backgroundColor = randomColor
        lblText.numberOfLines = 0
        lblText.preferredMaxLayoutWidth = screenWidth - 2 * margin
        
        lblRepostTitle?.numberOfLines = 0
        lblRepostTitle?.preferredMaxLayoutWidth = screenWidth - 2 * margin
        
        colFlowLayout.itemSize =  CGSize(width: itemWidth, height: itemWidth)
        colFlowLayout.minimumLineSpacing = 4
        colFlowLayout.minimumInteritemSpacing = 4
        
        self.selectionStyle = .none
    }

    //根据图片数量计算图片的大小
    //由于需要返回多个参数,采用元祖类型
    private func calculateCollectionSize(count:Int)-> (picSize:CGSize,cellSize:CGSize){
        //只有一张图,原尺寸
        if count == 0 {
            return (CGSize(width: 1, height: 1),CGSize(width: 1, height: 1))
        }
        
        if count == 1 {
            if let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: viewModel?.imageArray?.last?.wap360 ?? ""){
            
                let imageSize = image.size
                let maxWidth = screenWidth - 2 * margin
                if imageSize.width < maxWidth {
                    
                    return (imageSize,imageSize)
                }else{
                
                    return (CGSize(width: maxWidth, height: imageSize.height / imageSize.width * maxWidth),CGSize(width: maxWidth, height: imageSize.height / imageSize.width * maxWidth))
                    
                }

            }
            return (CGSize(width: itemWidth, height: itemWidth),CGSize(width: itemWidth, height: itemWidth))
        }
        //4张图,两行两列
        if count == 4 {
            let width = 2 * itemWidth + imageMargin
            return (CGSize(width: width, height: width),CGSize(width: itemWidth,height: itemWidth))
        }
        
        /*
        1,2,3
        5,6
        7,8,9
        */
        let row = CGFloat(( count - 1) / 3) + 1
        let height = row * itemWidth + (row - 1) * imageMargin
        return (CGSize(width: maxWidth, height: height),CGSize(width: itemWidth, height: itemWidth))
    }
  
    @IBAction func clickBtnMore(_ sender: UIButton) {
        let moreSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        let like = UIAlertAction(title: "收藏", style: .default) { (_) in
            print("123")
        }
        let cancle = UIAlertAction(title: "删除", style: .destructive, handler: nil)
        moreSheet.addAction(like)
        moreSheet.addAction(cancle)
//        let tarVc = self.findViewController()
//        
//        let pop = UIPopoverPresentationController(presentedViewController: tarVc!, presenting: moreSheet)
//        
//        pop.prese
//        self.findViewController()?.popoverPresentationController
        self.findViewController()?.present(moreSheet, animated: true, completion: nil)
    }
    
    
    
}
